package com.pds.web.testOrganizationInfo.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.pds.common.annotation.Log;
import com.pds.common.core.controller.BaseController;
import com.pds.common.core.domain.R;
import com.pds.common.core.page.TableDataInfo;
import com.pds.common.enums.BusinessType;
import com.pds.web.testOrganizationInfo.domain.PdsTestOrganizationPerson;
import com.pds.web.testOrganizationInfo.excel.OrganizationPersonExcel;
import com.pds.web.testOrganizationInfo.excel.OrganizationPersonListener;
import com.pds.web.testOrganizationInfo.excel.OrganizationPersonTemplate;
import com.pds.web.testOrganizationInfo.service.IPdsTestOrganizationPersonService;
import com.pds.web.testOrganizationInfo.util.EasyExcelUtil;
import com.pds.web.testOrganizationInfo.vo.PdsTestOrganizationPersonVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("/testOrganizationPerson")
public class PdsTestOrganizationPersonController extends BaseController {

    @Autowired
    private IPdsTestOrganizationPersonService pdsTestOrganizationPersonService;

    /**
     * 新增
     *
     * @param pdsTestOrganizationPerson
     * @return
     */
//    @Log(title = "机构信息新增人员信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public R<String> addPerson(@RequestBody PdsTestOrganizationPerson pdsTestOrganizationPerson) throws Exception {
//        String flag = pdsTestOrganizationPersonService.addPerson(pdsTestOrganizationPerson);
//        if ("姓名不能为空！".equals(flag)) {
//            return R.fail(null, "姓名不能为空！");
//        }
//        if ("手机号不能为空！".equals(flag)) {
//            return R.fail(null, "手机号不能为空！");
//        }
//        if ("账号已存在，注册失败！".equals(flag)) {
//            return R.fail(null, "账号已存在，注册失败！");
//        }
//        if ("不创建该人员账号".equals(flag)) {
//            return R.ok("人员信息添加成功，不创建该人员账号");
//        }
        return R.ok(pdsTestOrganizationPersonService.addPerson(pdsTestOrganizationPerson));
    }

    /**
     * 删除 -- 根据id
     *
     * @param id
     * @return
     */
//    @Log(title = "机构信息删除人员信息", businessType = BusinessType.DELETE)
    @GetMapping("/delete")
    public R<Boolean> deletePerson(@RequestParam Long id) throws Exception {
        return R.ok(pdsTestOrganizationPersonService.deletePerson(id));
    }

    /**
     * 更新
     *
     * @param pdsTestOrganizationPerson
     * @return
     */
//    @Log(title = "机构信息更新人员信息", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public R<Boolean> updatePerson(@RequestBody PdsTestOrganizationPerson pdsTestOrganizationPerson) throws Exception {
        return R.ok(pdsTestOrganizationPersonService.updatePerson(pdsTestOrganizationPerson));
    }

    /**
     * 查询 -- 分页/条件：userId，status
     *
     * @param pdsTestOrganizationPerson
     * @return
     */
    @GetMapping("/list")
    public TableDataInfo listPerson(PdsTestOrganizationPerson pdsTestOrganizationPerson) {
        startPage();
        List<PdsTestOrganizationPerson> list = pdsTestOrganizationPersonService.selectPersonList(pdsTestOrganizationPerson);

        return getDataTable(list);
    }

    /**
     * 查询检测机构用户列表
     * @param map
     *  - organizationId 环保局查询时需要传入id
     *  - personName 姓名
     *  - personCode 人员编码
     *  - phone 电话号码
     * @return
     * @throws Exception
     */
    @GetMapping("/getPersonList")
    public TableDataInfo getOrganizationPersonList(@RequestParam Map map) throws Exception {
        startPage();
        List<PdsTestOrganizationPersonVO> personList = pdsTestOrganizationPersonService.getOrganizationPersonList(map);
        return getDataTable(personList);
    }

    /**
     * 查询检测机构用户详细信息
     * @param id 主键ID
     * @return
     */
    @GetMapping("/getPersonInfo")
    public R<PdsTestOrganizationPersonVO> getPersonInfo(@RequestParam("id") Long id) throws Exception {
        return R.ok(pdsTestOrganizationPersonService.getPersonInfo(id));
    }

    /**
     * 下载人员模板
     *
     * @param response
     */
    @PostMapping("/downTemplate")
    public void downPersonTemplate(HttpServletResponse response) throws IOException {
        String fileName = URLEncoder.encode("机构人员模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        //用作需要传入的入参，如无须参数，则为空
        Map<String, String> map = new HashMap<>();
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet writeSheet = EasyExcelUtil.writeSelectedSheet(OrganizationPersonTemplate.class,
                0, "机构人员模板", map);
        //写
        List<OrganizationPersonTemplate> dataList = new ArrayList<>();
        OrganizationPersonTemplate template = new OrganizationPersonTemplate();
        template.setPersonName("示例：张三");
        dataList.add(template);
        excelWriter.write(dataList, writeSheet);
        //手动关闭
        excelWriter.finish();
    }

    /**
     * 导入机构人员
     *
     * @param file
     */
    @PostMapping("/importPerson")
    public R<String> importOrganizationPerson(MultipartFile file, Long organizationId) throws Exception {
        //获取文件名+后缀
        String filename = file.getOriginalFilename();
        if (filename != null) {
            //获取其后缀
            String extension = filename.substring(filename.lastIndexOf(".") + 1);
            if (!(extension.equals("xls") || extension.equals("xlsx"))) {
                //此处为自定义异常捕获,可使用其他方式
                throw new RuntimeException("文件格式有误,请检查上传文件格式");
            }
        }
        //获取文件的输入流
        InputStream inputStream = file.getInputStream();
        List<OrganizationPersonExcel> list = EasyExcel.read(inputStream) //调用read方法
                //注册自定义监听器，字段校验可以在监听器内实现
                .registerReadListener(new OrganizationPersonListener())
                .head(OrganizationPersonExcel.class) //对应导入的实体类
                .sheet(0) //导入数据的sheet页编号，0代表第一个sheet页，如果不填，则会导入所有sheet页的数据
                .headRowNumber(1) //列表头行数，1代表列表头有1行，第二行开始为数据行
                .doReadSync(); //开始读Excel，返回一个List<T>集合，继续后续入库操作
        Integer count = pdsTestOrganizationPersonService.importOrganizationPerson(list, organizationId);
        return R.ok(count + "条机构人员数据导入成功！");
    }
}
